// i.r(t), i.d(t, { default: () => WebVRLoader })
import { PreloadWebVr, PresentWebVr } from "../command/xr.command"
import EngineContext from "../EngineContext"
import { appTypeMin } from "../enum/appType.enum"
import funcUtil from "../utils/func.util"
import Logger from "../utils/Logger"
import vrPolyfill from "../utils/vr.polyfill"
import ApiClientModule from "./ApiClientModule"
import AppPhaseModule from "./AppPhaseModule"
import Module from "./Module"
import SettingsModule from "./SettingsModule"
const u = new Logger("webvr-loader")
export default class WebVRLoader extends Module {
  engine: EngineContext
  appPhaseModule: AppPhaseModule
  hackWebVRVersion: any
  vrDisplay: any
  constructor() {
    super(...arguments), (this.name = "webvr-loader")
  }
  async init(e, t: EngineContext) {
    this.engine = t
    this.onExitVr = this.onExitVr.bind(this)
    const i = await t.getModule(ApiClientModule)
    this.appPhaseModule = await t.getModule(AppPhaseModule)
    this.hackWebVRVersion = await i.getApi().getAppKey("SHOWCASE", "webvr_version")
    t.commandBinder.addBinding(PreloadWebVr, async () => this.hackLoadVrScript())
    t.commandBinder.addBinding(PresentWebVr, async () => this.hackEnterVrMode())
  }
  async maybeCacheVrDisplay() {
    const e = await vrPolyfill()
    e && (this.vrDisplay = e)
  }
  async hackEnterVrMode() {
    await this.maybeCacheVrDisplay()
    u.debug(`Presenting legacy webvr app to ${this.vrDisplay}`)
    if (this.vrDisplay) {
      u.info("Headset mounted")
      this.engine.deactivate()
      this.explosivelyDisableGui()
      try {
        this.appPhaseModule.updateActiveApp(appTypeMin.WEBVR)
      } catch (e) {
        throw Error("Error: Can't switch application mode at this time")
      }
    } else u.error("vrDisplay not found")
  }
  hackLoadVrScript() {
    const e = funcUtil.getUrlParams("webvr") || this.hackWebVRVersion
    u.debug(`Loading legacy webvr app version ${e}`)
    const t = "https://static.3dyunzhan.com/webvr/" + e + "/js/main"
    return new Promise(function (e, i) {
      const s = document.createElement("script")
      s.type = "text/javascript"
      s.src = t
      s.onload = e
      document.head.appendChild(s)
    })
  }
  onExitVr() {
    this.vrDisplay.isPresenting || (window.removeEventListener("vrdisplaypresentchange", this.onExitVr), u.info("Exiting VR"), this.hackUnload())
  }
  hackUnload() {
    let e = window.location.href
    ;-1 === window.location.search.indexOf("&qs=1") && (e += "&qs=1")
    window.location.replace(e)
  }
  explosivelyDisableGui() {
    const e = document.getElementById("gui")
    e && e.remove()
  }
}
